{% include "data/template-ui.html" %}
<link rel="stylesheet" type="text/css" href="/static/css/datatables/dataTables.bootstrap4.min.css" />
<link rel="stylesheet" type="text/css" href='/static/zTree/css/zTreeStyle.css'>

<style>
    .page-body {
        flex: 1;
        height: 0;
        overflow: auto;
        padding: 10px 15px;
        background: #fff;
    }
    #data_tree_wrapper {
        display: none;
        position: absolute;
        left: 280px;
        min-width: 200px;
        min-height: 300px;
        border-radius: 3px;
        box-shadow: 0 0 3px rgba(86, 96, 117, 0.7);
        background: #fff;
        z-index: 100;
    }
    #version {
        height: 32px;
        background-color: #FFFFFF;
        background-image: none;
        border: 1px solid #e5e6e7;
        border-radius: 1px;
        padding: 0px 12px;
        transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
        font-size: 14px;
    }
    #version:focus {
        border-color: #007bff !important;
    }
    .check-item {
        margin-bottom: 5px;
        padding: 10px 20px;
    }
    .check-item__title {
        display: inline-block;
        overflow: hidden;
        word-wrap: break-word;
        word-break: break-all;
        width: 100%;
        margin-bottom: 16px;
        text-align: left;
        vertical-align: top;
        border-bottom: 3px dotted #CCCCCC;
    }
    .check-item__title span {
        color: #238EFE;
        background-color: transparent;
        font-weight: bold;
    }
    .check-item__body {

    }
    .color-FF8400 {
        color: #FF8400;
    }
    #chart1, #chart2, #chart3 {
        width: 100%;
        height: 400px;
        padding: 0 80px;
    }
    #chart1, #chart2 {
        padding: 15px 0;
    }
    .table thead th {
        background-color: #EDF4FA;
        color: #66718E;
    }
    .table th, .table td, .dataTables_scrollHead th, .dataTables_scrollBody td {
        padding: 0 !important;
        font-size: 12px;
    }
</style>

<div class="container-fluid animated fadeInUp">
    <!-- 标题 -->
    <div class="row page-titles">
        <div class="col-md-12 align-self-center" style="display: flex;align-items: center">
            <h3 class="text-primary" style="margin-right: 30px">数据质量检查报告</h3>
            <div>
                <label for="version" style="margin-bottom:0">数据期：</label>
                <input id="version" name="version" type="text" autocomplete="off">
                <div id="data_tree_wrapper">
                    <ul id="data_tree" class="ztree"></ul>
                </div>
            </div>
            <button onclick="search();" class="btn btn-primary btn-sm" style="margin-left: 30px">
                <i class="fa fa-search"></i>查询
            </button>
        </div>
    </div>
    <div class="page-body">
        <div class="check-item">
            <div class="check-item__title">
                <span style="font-size: 24px;">01</span>
                <span style="font-size: 18px;">数据质量综合评分</span>
            </div>
            <div class="check-item__body">
                <div>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span class="color-FF8400" id="span-version1"></span>
                    <span>数据质量综合评分为</span>
                    <span class="color-FF8400" id="span-total"></span>
                    <span>分，比上期增长</span>
                    <span class="color-FF8400" id="span-increase"></span>
                    <span>。近期评分情况如下所示：</span>
                </div>
                <div id="chart1"></div>
                <table id="table1" class="table table-bordered" style="width:100%">
                    <thead>
                    <tr>
                        <th>数据期</th>
                        <th>本期评分</th>
                        <th>上期评分</th>
                        <th>增长分数</th>
                        <th>增长率</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
        <div class="check-item">
            <div class="check-item__title">
                <span style="font-size: 24px;">02</span>
                <span style="font-size: 18px;">数据质量检查错误情况</span>
            </div>
            <div class="check-item__body">
                <div>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span class="color-FF8400" id="span-version2"></span>
                    <span>错误次数达</span>
                    <span class="color-FF8400" id="span-errNum"></span>
                    <span>条，约占检查次数的</span>
                    <span class="color-FF8400" id="span-errPer">20.01%</span>
                    <span>。近期错误情况如下所示：</span>
                </div>
                <div id="chart2"></div>
                <table id="table2" class="table table-bordered" style="width:100%">
                    <thead>
                    <tr>
                        <th>数据期</th>
                        <th>检查次数</th>
                        <th>错误次数</th>
                        <th>错误占比</th>
                        <th>评分</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
        <div class="check-item">
            <div class="check-item__title">
                <span style="font-size: 24px;">03</span>
                <span style="font-size: 18px;">规则数据质量情况</span>
            </div>
            <div class="check-item__body">
                <div>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span class="color-FF8400" id="span-version3"></span>
                    <span>按照质控规则分类检查的报送数据质量情况如下。其中：</span>
                    <span class="color-FF8400" id="span-checkType">空值检查，引用完整性检查</span>
                    <span>等规则的错误次数较多,尤其是</span>
                    <span class="color-FF8400" id="span-checkType-important">空值检查</span>
                    <span>，需要重视。</span>
                </div>
                <div id="chart3"></div>
                <table id="table3" class="table table-bordered" style="width:100%">
                    <thead>
                    <tr>
                        <th>规则类型</th>
                        <th>检查次数</th>
                        <th>错误次数</th>
                        <th>错误占比</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>

</div>
</div>

<script type="text/javascript" src="/static/js/DataTables/DataTables-1.10.18/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="/static/js/DataTables/DataTables-1.10.18/js/dataTables.bootstrap.js"></script>
<script src='/static/zTree/js/jquery.ztree.core.min.js'></script>
<script src='/static/zTree/js/fuzzysearch.js'></script>
<script src='/static/zTree/js/jquery.ztree.exhide.min.js'></script>
<script src='/static/zTree/js/jquery.ztree.exedit.js'></script>

<script type="text/javascript" class="init">
    let company = "{{ company }}";
    let setting = {
        data: {
            key: {
                name: 'id',
                title: 'id'
            },
            simpleData: {
                enable: true,
                pIdKey: 'pid'
            }
        },
        callback: {
            onClick: onNodeClick
        },
    };
    let chart1 = null, chart2 = null, chart3 = null;
    let option1 = {
        color: ["#1DCBFE", "#FF974A"],
        title: {
            text: '各数据期数据质量评分情况',
            x:'center',
            textStyle: {
                fontSize: 18,
                color: '#67757c'
            }
        },
        grid: {
            left: 80,
            top: 40,
            bottom: 40,
            right: 80
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return `
                    ${params[0].name}
                    <br/>
                    ${params[0].marker}
                    <span>${params[0].seriesName}: ${params[0].value}</span>
                    <br/>
                    ${params[1].marker}
                    <span>${params[1].seriesName}: ${(params[1].value * 100).toFixed(2) + '%'}</span>
                `;
            }
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: [{
            name: '评分',
            type: 'value',
            splitLine: {
                show: true,
                lineStyle:{
                    type:'dashed'
                }
            }
        }, {
            name: '增长率',
            type: 'value',
            axisLabel: {
                show: true,
                interval: 'auto', //居中显示
            },
        }],
        legend: {
            x:'right',
            padding:[0, 120, 0, 0],
            data: ['评分', '增长率']
        },
        series: []
    };
    let option2 = {
        color: ["#32AEFF", "#FF974A"],
        title: {
            text: '各数据期检查错误情况',
            x:'center',
            textStyle: {
                fontSize: 18,
                color: '#67757c'
            }
        },
        grid: {
            left: 80,
            top: 40,
            bottom: 40,
            right: 80
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                return `
                    ${params[0].name}
                    <br/>
                    ${params[0].marker}
                    <span>${params[0].seriesName}: ${params[0].value}</span>
                    <br/>
                    ${params[1].marker}
                    <span>${params[1].seriesName}: ${(params[1].value * 100).toFixed(2) + '%'}</span>
                `;
            }
        },
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: [{
            name: '错误次数',
            type: 'value',
            splitLine: {
                show: true,
                lineStyle:{
                    type:'dashed'
                }
            }
        }, {
            name: '错误占比',
            type: 'value',
            axisLabel: {
                show: true,
                interval: 'auto', //居中显示
            },
        }],
        legend: {
            x:'right',
            padding:[0, 120, 0, 0],
            data: ['错误次数', '错误占比']
        },
        series: []
    };
    let option3 = {
        tooltip: {
            formatter: '{a} <br/>{b} : {c}%'
        },
        toolbox: {
            feature: {
                restore: {},
                saveAsImage: {}
            }
        },
        series: [
            {
                name: '错误占比',
                type: 'gauge',
                radius: '90%',
                center: ['50%', '55%'],
                detail: { formatter: '{value}%' },
                axisLine: {            // 坐标轴线
                    lineStyle: {       // 属性lineStyle控制线条样式
                        color: [[0.2, '#60ACFC'], [0.8, '#01B300'], [1, '#FE6C00']]
                    }
                },
                data: [{ name: '错误占比', value: 0 }]
            }
        ]
    };

    $(document).ready(function () {
        chart1 = echarts.init(document.getElementById('chart1'));
        chart2 = echarts.init(document.getElementById('chart2'));
        chart3 = echarts.init(document.getElementById('chart3'));

        initSearch();
        getVersionTreeData().then(res => {
            if (res.stat !== 200) return;
            initVersionTree(res.data);
            search();
        });
    });

    // 获取期数树的数据
    function getVersionTreeData() {
        return $post("../../api/dashboard/model_page_info_version_all", {
            company: company,
            startTime: $('#datepicker-start').val(),
            endTime: $('#datepicker-end').val()
        }).then(result => {
            return result;
        }).catch(e => {
            console.error(e);
        });
    }

    // 初始化树
    function initVersionTree(data) {
        let tree = $.fn.zTree.init($("#data_tree"), setting, data);
        fuzzySearch('data_tree', '#version', null, null); //初始化模糊搜索方法
        tree.expandNode(tree.getNodeByTId('data_tree_1'));
        let firstChildNode = tree.getNodeByTId('data_tree_2');
        if (firstChildNode) {
            tree.selectNode(firstChildNode);
        }
        $('#version').val(firstChildNode.id);
        $('#version').attr('version', firstChildNode.check_version);
    }

    //初始化搜索
    function initSearch() {
        $('#version').click(function() {
            $('#data_tree_wrapper').css('display', 'block');
        });
        $('#version').blur(function() {
            $('#data_tree_wrapper').css('display', 'none');
        });
        $("#data_tree_wrapper").on("mousedown ", function () {
            event.preventDefault();
        });
    }

    // 点击进行搜索
    function search() {
        let version = $('#version').attr('version');
        let versionVal = $('#version').val();
        $('#span-version1').html(versionVal);
        $('#span-version2').html(versionVal);
        $('#span-version3').html(versionVal);

        getScoreData(version).then(data => {
            if (data.length === 0) return;

            data.forEach(v => {
                v.coefficient_tb = v.coefficient_tb === '--' ? null : v.coefficient_tb;
            });

            $('#span-total').html(data[0].total_coefficient);
            $('#span-increase').html((data[0].coefficient_tb * 100).toFixed(2) + '%');
            $('#span-errNum').html(data[0].result_err);
            $('#span-errPer').html((data[0].bl * 100).toFixed(2) + '%');

            option1.series = [];
            option2.series = [];
            setChart1(data);
            setChart2(data);
            setTable1(data);
            setTable2(data);
        });
        getDescData(version).then(data => {
            let types = [], importantType = '', currNum = 0;
            data.forEach(v => {
                if (v.problem_type !== '总计') {
                    types.push(v.problem_type);
                    if (v.result_err > currNum) {
                        importantType = v.problem_type;
                        currNum = v.result_err;
                    }
                }
            });

            $('#span-checkType').html(types.join(','));
            $('#span-checkType-important').html(importantType);

            setChart3(data);
            setTable3(data);
        });
    }

    // 点击数的节点
    function onNodeClick(event, treeId, treeNode, clickFlag) {
        if (!treeNode.isParent) {
            $('#version').blur(function() {
                $('#data_tree_wrapper').css('display', 'none');
            });
            $('#version').val(treeNode.id);
            $('#version').attr('version', treeNode.check_version);
            $('#data_tree_wrapper').css('display', 'none');
        }
    }

    function getScoreData(version) {
        chart1.showLoading({
            text: '加载中...',
            textStyle: { fontSize : 30 , color: '#60acfc' },
            effectOption: { backgroundColor: 'rgba(0, 0, 0, 0)' }
        });
        chart2.showLoading({
            text: '加载中...',
            textStyle: { fontSize : 30 , color: '#60acfc' },
            effectOption: { backgroundColor: 'rgba(0, 0, 0, 0)' }
        });
        return $post("../../api/quality/model_comprehensive_score", {
            company: company,
            check_version: version
        }).then(res => {
            chart1.hideLoading();
            chart2.hideLoading();
            if (res.stat != 200) {
                showText($('#chart1'), '请求失败');
                showText($('#chart2'), '请求失败');
                return [];
            }
            if (res.data.length === 0) {
                showText($('#chart1'), '暂无数据');
                showText($('#chart2'), '暂无数据');
            }
            return res.data;
        }).catch(e => {
            console.error(e);
            chart1.hideLoading();
            chart2.hideLoading();
        });
    }

    function getDescData(version) {
        chart3.showLoading({
            text: '加载中...',
            textStyle: { fontSize : 30 , color: '#60acfc' },
            effectOption: { backgroundColor: 'rgba(0, 0, 0, 0)' }
        });
        return $post("../../api/quality/model_quality_desc", {
            company: company,
            check_version: version
        }).then(res => {
            chart3.hideLoading();
            if (res.stat != 200) {
                showText($('#chart3'), '请求失败');
                return [];
            }
            if (res.data.length === 0) {
                showText($('#chart3'), '暂无数据');
            }
            return res.data;
        }).catch(e => {
            console.error(e);
            chart3.hideLoading();
        });
    }

    function setChart1(data) {
        let xAxis = [], total_coefficient = [], coefficient_tb = [];
        data.forEach(v => {
            xAxis.push(v.check_version);
            total_coefficient.push(v.total_coefficient);
            coefficient_tb.push(v.coefficient_tb);
        });

        option1.xAxis.data = xAxis;
        option1.series = [{
            type: 'bar',
            barMaxWidth: 150,
            name: '评分',
            data: total_coefficient,
        }, {
            type: 'line',
            name: '增长率',
            data: coefficient_tb,
            yAxisIndex: 1
        }];
        chart1.setOption(calcScale(option1));
    }

    function setChart2(data) {
        let xAxis = [], result_err = [], bl = [];
        data.forEach(v => {
            xAxis.push(v.check_version);
            result_err.push(v.result_err);
            bl.push(v.bl);
        });

        option2.xAxis.data = xAxis;
        option2.series = [{
            type: 'bar',
            barMaxWidth: 150,
            name: '错误次数',
            data: result_err,
        }, {
            type: 'line',
            name: '错误占比',
            data: bl,
            yAxisIndex: 1
        }];
        chart2.setOption(calcScale(option2));
    }

    function setChart3(data) {
        if (data.length === 0) return

        option3.series[0].data[0].value = (data[0].err_per * 100).toFixed(2);
        chart3.setOption(option3);
    }

    function setTable1(data) {
        let table = $('#table1').DataTable({
            destroy: true,
            searching: false,
            ordering: false,
            info: false,
            paging: false,
            fixedHeader: true, // 固定表头
            stateSave: true,
            pagingType: "full_numbers",
            sLoadingRecords: "正在加载数据...",
            data: data,
            columns: [
                { data: 'check_version'},
                { data: 'total_coefficient'},
                { data: 'total_coefficient_pre'},
                { data: 'total_coefficient_diff'},
                { data: 'coefficient_tb'}
            ],
            columnDefs: [{
                targets: 3,
                data: null,
                render: function (data, type, row) {
                    return ((row.total_coefficient || 0) - (row.total_coefficient_pre || 0)).toFixed(2);
                }
            }, {
                targets: 4,
                data: null,
                render: function (data, type, row) {
                    let value = (row.coefficient_tb * 100).toFixed(2) + '%';
                    return row.coefficient_tb === null ? '--' : value;
                }
            }]
        });
    }

    function setTable2(data) {
        let table = $('#table2').DataTable({
            destroy: true,
            searching: false,
            ordering: false,
            info: false,
            paging: false,
            fixedHeader: true, // 固定表头
            stateSave: true,
            pagingType: "full_numbers",
            sLoadingRecords: "正在加载数据...",
            data: data,
            columns: [
                { data: 'check_version'},
                { data: 'result'},
                { data: 'result_err'},
                { data: 'bl'},
                { data: 'total_coefficient'}
            ],
            columnDefs: [{
                targets: 3,
                data: null,
                render: function (data, type, row) {
                    return row.bl === 0 ? '0%' : (row.bl * 100).toFixed(2) + '%';
                }
            }]
        });
    }

    function setTable3(data) {
        let table = $('#table3').DataTable({
            destroy: true,
            searching: false,
            ordering: false,
            info: false,
            paging: false,
            fixedHeader: true, // 固定表头
            stateSave: true,
            pagingType: "full_numbers",
            sLoadingRecords: "正在加载数据...",
            data: data,
            columns: [
                { data: 'problem_type'},
                { data: 'result'},
                { data: 'result_err'},
                { data: 'err_per'},
            ],
            columnDefs: [{
                targets: 3,
                data: null,
                render: function (data, type, row) {
                    return row.err_per === 0 ? '0%' : (row.err_per * 100).toFixed(2) + '%';
                }
            }]
        });
    }

    function calcScale(option) {
        let leftMax = Math.max(...option.series[0].data);   // 找出最大值
        leftMax = parseInt(leftMax) + '';    // 取整并转为字符串
        if (leftMax.length <= 2) { // 0-100的数（业务上没有负值）
            leftMax = Math.ceil(leftMax / 5) * 5;
        } else {
            let len = leftMax.length;
            let topTwo = leftMax.substr(0, 2);
            leftMax = Math.ceil(topTwo / 5) * 5 * Math.pow(10, len - 2);
        }
        option.yAxis[0].min = 0;
        option.yAxis[0].max = leftMax;
        option.yAxis[0].interval = leftMax / 5;

        // 两个图的右轴都是小数（增长率/错误占比）
        let rightMax = 0, rightMin = 0;        if (option.series[1].data.filter(v => v < 0).length) { // 有负数
            rightMax = Math.max(...option.series[1].data);
            rightMin = Math.min(...option.series[1].data)
            rightMax = rightMax - rightMin;
        }
        rightMax = (rightMax - (rightMin > 0 ? 0 : rightMin)).toFixed(4) * 10000 + '';    // 取整并转为字符串
        if (rightMax.length <= 2) {
            rightMax = Math.ceil(rightMax / 5) * 5;
        } else {
            let len = rightMax.length;
            let topTwo = rightMax.substr(0, 2);
            rightMax = Math.ceil(topTwo / 5) * 5 * Math.pow(10, len - 2);
        }
        if (rightMin < 0) {
            option.yAxis[1].min = Math.floor(rightMin * 10000 / (rightMax / 5)) * (rightMax / 5) / 10000;
            option.yAxis[1].max = rightMax / 10000 + option.yAxis[1].min;
            option.yAxis[1].interval = (option.yAxis[1].max - option.yAxis[1].min) /5;
        } else {
            option.yAxis[1].min = 0;
            option.yAxis[1].max = rightMax / 10000;
            option.yAxis[1].interval = rightMax / 50000;
        }
        if (option.yAxis[1].min === 0 && option.yAxis[1].max === 0) {
            option.yAxis[1].max = 1;
            option.yAxis[1].interval = 0.2;
        }
        return option;
    }
</script>
</body>
</html>